﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace BoriPeter.FatSecret
{
    public static class Deserializer
    {
        public static T XmlFromString<T>(string objectData)
        {
            var result = (T)XmlFromString(objectData, typeof(T));
            if (result != null)
                return result;
            else
                return (T)Activator.CreateInstance(typeof(T));
        }

        public static object XmlFromString(string objectData, Type type)
        {
            object result = null;
            try
            {
                var serializer = new XmlSerializer(type);

                using (TextReader reader = new StringReader(objectData))
                {
                    result = serializer.Deserialize(reader);
                }
            }
            catch (Exception)
            {
                /* TODO handling exception
                result = null;
                ErrorModel errorResult;
                var serializer = new XmlSerializer(typeof(ErrorModel));

                using (TextReader reader = new StringReader(objectData))
                {
                    errorResult = (ErrorModel)serializer.Deserialize(reader);
                }
                if (errorResult != null)
                {
                    Debug.WriteLine("Error Code: {0}, Error Message: {1}", errorResult.Code, errorResult.Message);
                }*/
            }

            return result;
        }
    }
}
